package com.bdweb.mokuai;

import com.bdweb. mokuai.logWrite;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class getUDPhex{
    public getUDPhex(String ASCII,String ip,int port) throws IOException {
        byte[] bytes = hexStrToBinaryStr(ASCII);
        InetAddress address=InetAddress.getByName(ip);//ip
        DatagramSocket d = new DatagramSocket(6600);//参数可以指定发送端的端口
            //创建一个发送端对象,,发送端自带默认端口号
            //创建一个数据包对象封装数据
            //byte[] buffer = ASCII.getBytes();
            DatagramPacket dd = new DatagramPacket(bytes, bytes.length, address, port);
            new logWrite(dd.getSocketAddress()+"连接成功");
            //发送数据
            d.send(dd);
            d.close();
        }

    private static byte[] hexStrToBinaryStr(String hexString) {

        if (hexString.length()==0) {
            return null;
        }

        hexString = hexString.replaceAll(" ", "");

        int len = hexString.length();
        int index = 0;

        byte[] bytes = new byte[len / 2];

        while (index < len) {

            String sub = hexString.substring(index, index + 2);

            bytes[index/2] = (byte)Integer.parseInt(sub,16);

            index += 2;
        }


        return bytes;
    }
}
